<?php
/*
 * @Author: zwx
 * @Date: 2024-08-18 16:40:12
 * @LastEditors: zwx
 * @LastEditTime: 2024-10-13 23:28:54
 * @Description: 从视频号拉取公域订单
 */

namespace app\apiadmin\controller\gongyu;

use app\apiadmin\controller\liveManager\LiveStatus;
use app\common\controller\BaseController;
use app\common\utils\Curl;
use LaneWeChat\Core\Msg;
use LaneWeChat\Core\MsgConstant;
use think\facade\Db;
use think\facade\Log;

class GetOrdersFromSPH extends BaseController
{

    public function __construct()
    {

    }


    /*****************************        视频号-毛毛虫李洁的小店                     *******************************************************8 */
    /**
     * 获取视频号小店Access_Token
     * @param $keys  存储token的字段名
     * @param $appid 程序appid
     * @param $appsecret   程序的密钥
     */
    public static function getSPShopAccessToken()
    {
        //检测本地是否已经拥有access_token，并且检测access_token是否过期
        $accessToken = self::_checkSPShopAccessToken();
        if ($accessToken === false) {
            $accessToken = self::_getSPShopAccessToken();
        }
        return $accessToken['access_token'];
    }

    /**
     * 获取视频号小店accesstoken
     * @param $keys  存储token的字段名
     * @param $appid 程序appid
     * @param $appsecret   程序的密钥
     * @return error|string
     */
    private static function _getSPShopAccessToken()
    {
        $appid = 'wx16f464c7db7809b2';
        $secret = '3c97bcd0ad3ba5a7b643371b5b133941';

        // $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.WA_SHOP_APPID.'&secret='.WA_SHOP_APPSECRET;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $secret;
        $accessToken = Curl::callWebServer($url, '', 'GET');
        if (!isset($accessToken['access_token'])) {
            file_put_contents('shptoken_error.txt', date('Y-m-d H:i:s') . ' 获取ACCESS_TOKEN失败' . json_encode($accessToken) . "\r\n", FILE_APPEND);
            return false;
        }

        //我们把token保存在数据库中
        $accessToken['time'] = time();
        Db::table('xh_common')->update(array('keys' => 'weapp_SPH_shop_token', 'values' => serialize($accessToken)));
        return $accessToken;
    }

    /**
     * 检测视频号小店ACCESS_TOKEN是否过期
     * -10s是预留的网络延迟时间
     *  @param $keys  存储token的字段名
     * @return bool
     */
    private static function _checkSPShopAccessToken()
    {
        $data = Db::table('xh_common')->where(array('keys' => 'weapp_SPH_shop_token'))->find();
        if ($data) {
            $data = unserialize($data['values']);
            if ($data && time() - $data['time'] < $data['expires_in'] - 10) {
                return $data;
            }
        }
        return false;
    }



    /**********************************      获取订单             **********************************************/


    /**
     * 拉取视频号小商店订单
     */
    public function getDingDanFromSPShop($next_key = '')
    {
        $appid = 'wx16f464c7db7809b2';

        // $this->cancelOrder_shipinhao6();
        header("Content-type: text/html; charset=utf-8");
        // $start_create_time = I('start_create_time');
        // $start_time = strtotime(date("Y-m-d H:i:s", strtotime("-2 minute")));
        // $end_time = strtotime(date("Y-m-d H:i:s", time()));
        $start_time = strtotime(date("Y-m-d", time()));
        $end_time = strtotime(date("Y-m-d H:i:s", time()));

        //获取本地存储的订单数组
        // $order = Db::table('xh_common')->where(array('keys'=>WEAPP_SHOP_ORDER))->getFields('values');
        // $order = unserialize($order);


        // 拉取视频号小商店待发货订单
        $accessToken = $this->getSPShopAccessToken();
        $queryUrl = 'https://api.weixin.qq.com/channels/ec/order/list/get?access_token=' . $accessToken;
        $data = array();
        $data['create_time_range']['start_time'] = $start_time;
        $data['create_time_range']['end_time'] = $end_time;
        $data['status'] = 20;   //20：待发货；10：待付款   250取消
        $data['page_size'] = 100;
        if (!empty($next_key)) {
            $data['next_key'] = $next_key;
        }
        $template = json_encode($data);
        $order2 = Curl::callWebServer($queryUrl, $template, 'POST');
        dump($order2);
        //没有订单返回
        if (count($order2['order_id_list']) == 0) {
            // $this->ajaxReturn(array('s'=>0,'msg'=>'小商店无订单','data'=>$order2));
            return;
        }


        //订单数组
        $orderlist = array();
        $delivery = array();
        $ids = $order2['order_id_list'];  //循环出小商店订单的订单号数组

        //与本地存储的数据进行比较排重，筛选出需要添加的订单
        $where = [];
        $where[] = ['order_num', 'in', $ids];
        $yiyou1 = Db::table('xh_order_1')->where($where)->field('order_num')->select()->toArray();
        $yiyou = array_column($yiyou1, 'order_num');

        if ($yiyou) {
            $addids = array_diff($ids, $yiyou);
        } else {
            $addids = $ids;
        }


        if (!$addids) {
            dump('重复订单，无需添加');

            //如果还有其他页数据，则循环继续
            dump($order2['has_more']);
            if ($order2['has_more']) {
                $this->getDingDanFromSPShop($order2['next_key']);
            }
            dump($order2['next_key']);
            return;
        }

        //根据orderid获取order详细信息
        foreach ($addids as $k => $v) {
            // 拉取视频号小商店待发货订单
            $accessToken = $this->getSPShopAccessToken();
            $queryUrl = 'https://api.weixin.qq.com/channels/ec/order/get?access_token=' . $accessToken;
            $data = array();
            $data['order_id'] = $v;
            $template = json_encode($data);
            $data = Curl::callWebServer($queryUrl, $template, 'POST');

            if ($data['errmsg'] != 'ok') {
                return;
            }
            $order2['orders'][] = $data['order'];
        }
        dump($order2);
        //组装订单数据
        foreach ($order2['orders'] as $k => $v) {
            foreach ($addids as $k1 => $v1) {
                if ($v['order_id'] == $v1) {
                    foreach ($v['order_detail']['product_infos'] as $k2 => $v2) {
                        $where = [];
                        $where[] = ['xh_course_product.product_id', '=', $v2['product_id']];
                        $course = Db::table('xh_course')
                            ->field('xh_course.*')
                            ->join('xh_course_product', 'xh_course_product.courseid = xh_course.id', 'inner')
                            ->where($where)->find();
                        $a = array();
                        $a['courseid'] = $course['id'];
                        $a['del'] = 0;
                        $a['time'] = $v['create_time'];
                        // $a['fenzhan']=;
                        // $a['number']=;
                        $a['price'] = $v2['sale_price'] / 100;
                        $a['pay_state'] = 1;
                        //生成内部订单号

                        $a['out_trade_no'] = $v['order_id'] . '';
                        $a['fee'] = $v2['sale_price'] / 100;
                        $a['refund_fee'] = 0;
                        if ($v['order_detail']['delivery_info']['address_info']['tel_number'] != '') {
                            $a['tel'] = $v['order_detail']['delivery_info']['address_info']['tel_number'];
                        }
                        if ($v['order_detail']['delivery_info']['address_info']['virtual_order_tel_number'] != '') {
                            $a['tel'] = $v['order_detail']['delivery_info']['address_info']['virtual_order_tel_number'];
                        }
                        $a['items'] = '英语课程费';
                        $a['goods_detail'] = '[{"id":8,"fee":"' . ($v2['sale_price'] / 100) . '.00","name":"\u82f1\u8bed\u8bfe\u7a0b\u8d39"}]';
                        $a['params'] = '{"remark":"\u8d2d\u4e70\u82f1\u8bed\u8bfe\u7a0b","price":"' . ($v2['sale_price'] / 100) . '.00","courseid":"' . $course['id'] . '",tichengtype":0,"ticheng":"0.00","tichengmoney":0.000}';
                        $a['order_num'] = $v['order_id'] . '';
                        $a['order_nums'] = $v['order_id'] . '';
                        $a['result'] = '';
                        // $a['isfinished'] = 1;
                        $a['paymethod'] = 1;
                        $a['flag'] = 9;
                        $a['pay_time'] = $v['order_detail']['pay_info']['pay_time'];
                        $a['refund_time'] = 0;
                        $a['operator'] = '视频号-蓝图计划';
                        $a['manager'] = '视频号-蓝图计划';
                        $a['weapp_openid'] = $v['openid'];
                        $a['ticheng'] = 0;
                        $a['tichengmoney'] = 0;
                        $a['tichengtype'] = 0;
                        $a['laiyuan'] = 1;
                        $a['province'] = $v['order_detail']['delivery_info']['address_info']['province_name'];
                        $a['city'] = $v['order_detail']['delivery_info']['address_info']['city_name'];
                        $a['county'] = $v['order_detail']['delivery_info']['address_info']['county_name'];
                        $a['addr'] = $v['order_detail']['delivery_info']['address_info']['detail_info'];

                        //前端显示数据
                        $a['title'] = $v2['title'];
                        if ($v['order_detail']['delivery_info']['address_info']['tel_number'] != '') {
                            $a['tel_number'] = $v['order_detail']['delivery_info']['address_info']['tel_number'];
                        }
                        if ($v['order_detail']['delivery_info']['address_info']['virtual_order_tel_number'] != '') {
                            $a['tel_number'] = $v['order_detail']['delivery_info']['address_info']['virtual_order_tel_number'];
                        }
                        $a['user_name'] = $v['order_detail']['delivery_info']['address_info']['user_name'];
                        $a['city_name'] = $v['order_detail']['delivery_info']['address_info']['city_name'];
                        $a['county_name'] = $v['order_detail']['delivery_info']['address_info']['county_name'];
                        $a['create_time'] = $v['create_time'];

                        $a['waijiao'] = $this->shoumaiguize($course['id']);  //售卖规则
                        $a['i_id'] = $v2['product_id'];
                        $a['shop_id'] = $appid;

                        $orderlist[] = $a;

                        //配送单
                        $b = array();
                        $b['order_num'] = $v['order_id'] . '';
                        $b['order_time'] = strtotime($v['order_detail']['pay_info']['pay_time']);
                        if ($v['order_detail']['delivery_info']['address_info']['tel_number'] != '') {
                            $b['tel'] = $v['order_detail']['delivery_info']['address_info']['tel_number'];
                        }
                        if ($v['order_detail']['delivery_info']['address_info']['virtual_order_tel_number'] != '') {
                            $b['tel'] = $v['order_detail']['delivery_info']['address_info']['virtual_order_tel_number'];
                        }
                        $b['name'] = $v['order_detail']['delivery_info']['address_info']['user_name'];
                        $b['address'] = $v['order_detail']['delivery_info']['address_info']['province_name'] . $v['order_detail']['delivery_info']['address_info']['city_name'] . $v['order_detail']['delivery_info']['address_info']['county_name'] . $v['order_detail']['delivery_info']['address_info']['detail_info'];
                        $b['goods'] = $course['title'];
                        $b['laiyuan'] = 1;
                        $b['time'] = time();
                        $delivery[] = $b;

                        //发短信
                        // $sms = array();
                        // $sms = explode('+', $a['tel']);
                        // $res = \VodAPI::smsToMember($sms);
                        // dump($res);
                    }
                    continue;
                }
            }
        }

        // dump($orderlist);
        // dump($delivery);

        //添加新订单

        //向小雪花后台添加数据
        $this->addXXHOrder($orderlist, 1);
        return;
    }

    /**
     * @author: zwx
     * @Description: 将订单数据同步到小雪花后台
     * @param {*} $a
     * @Date: 2024-03-14 18:22:29
     */
    public function addXXHOrder($orderlist, $state)
    {
        $qiyeid = '1';
        $c = array();
        $e = array();
        foreach ($orderlist as $k => $a) {
            $where = [];
            $where[] = ['product_id', 'like', '%' . $a['i_id'] . '%'];
            $product = Db::table('xh_course_product')->where($where)->find();
            // dump(Db::table('xh_course_product', 'xh_', C('DB_CONFIG_XIAOXUEHUA'))->where(array('product_id' => array('like', '%' . $a['i_id'] . '%')))->fetchSql()->find());
            $qiyeid = $product['qiyeid'];
            $laiyuan = Db::table('xh_app_laiyuan')->where('name', $a['manager'])->find();



            $b = array();
            $b['courseid'] = $product['courseid'];
            $b['out_order_no'] = $a['out_trade_no'];
            $b['order_num'] = $a['order_num'];
            $b['order_nums'] = $a['order_nums'];
            $b['total_fee'] = $a['fee'] * 100;
            $b['pingtai'] = $laiyuan['pingtaiid']; //1:抖音
            $b['laiyuan'] = $laiyuan['id'];
            $b['app_id'] = $a['shop_id'];
            $b['time'] = date('Y-m-d H:i:s', $a['time']);
            $b['del'] = 0;
            if ($a['tel']) {
                $b['tel'] = $a['tel'];
            } else {
                $b['tel'] = '';
            }

            $b['order_status'] = $state;
            $b['pay_method'] = $a['paymethod'];
            $b['pay_state'] = 1;
            $b['pay_time'] = date('Y-m-d H:i:s', $a['pay_time']);

            $b['jinrufangshi'] = '';

            //达人信息
            $b['referrer_id'] = isset($a['referrer_id']) ? $a['referrer_id'] : '';
            $b['referrer_name'] = isset($a['referrer_name']) ? $a['referrer_name'] : '';

            $b['waijiao'] = $this->shoumaiguize($product['courseid']);  //售卖规则


            $c[] = $b;

            //存储id临时表
            $d = array();
            $d['courseid'] = $b['courseid'];
            $d['order_num'] = $b['order_num'];
            $d['out_order_no'] = $b['out_order_no'];
            $d['state'] = 1;
            $d['tel'] = $b['tel'];
            $d['time'] = $b['time'];
            $d['app_id'] = $b['app_id'];
            $d['qiyeid'] = $qiyeid;
            $d['pingtai'] = $laiyuan['pingtaiid']; //1:抖音
            $d['laiyuan'] = $laiyuan['id'];

            $e[] = $d;

        }

        Db::table('xh_ordernum')->insertAll($e);
        Db::table('xh_order_1')->insertAll($c);
        //给订单打短码标签
        if ($e) {
            foreach ($e as $k => $v) {
                $this->dabiaoqian($v);
            }
        }

        //预分配
        $order_nums = array_column($orderlist, 'order_num');
        $this->batchAutoDistributionApi($order_nums);

    }


    /**
     * 拉取视频号小商店订单   根据单号单次拉取
     */
    public function getDingDanFromSPShop_one($order_num, $state)
    {

        $where = [];
        $where[] = ['order_num', '=', $order_num];

        $o = Db::table('xh_order_1')->where($where)->field('order_num')->select()->toArray();
        dump(2222);
        if (!empty($o)) {
            dump($o);
            return 2;
        }

        $appid = 'wx16f464c7db7809b2';

        // $this->cancelOrder_shipinhao6();
        header("Content-type: text/html; charset=utf-8");


        //根据orderid获取order详细信息
        // 拉取视频号小商店待发货订单
        $accessToken = $this->getSPShopAccessToken();
        $queryUrl = 'https://api.weixin.qq.com/channels/ec/order/get?access_token=' . $accessToken;
        $data = array();
        $data['order_id'] = $order_num;
        $template = json_encode($data);
        $data = Curl::callWebServer($queryUrl, $template, 'POST');
        dump($data);
        if ($data['errmsg'] != 'ok') {
            return;
        }
        $order2['orders'][] = $data['order'];

        //组装订单数据
        foreach ($order2['orders'] as $k => $v) {
            foreach ($v['order_detail']['product_infos'] as $k2 => $v2) {
                $where = [];
                $where[] = ['xh_course_product.product_id', '=', $v2['product_id']];
                $course = Db::table('xh_course')
                    ->field('xh_course.*')
                    ->join('xh_course_product', 'xh_course_product.courseid = xh_course.id', 'inner')
                    ->where($where)->find();
                $a = array();
                $a['courseid'] = $course['id'];
                $a['del'] = 0;
                $a['time'] = $v['create_time'];
                // $a['fenzhan']=;
                // $a['number']=;
                $a['price'] = $v2['sale_price'] / 100;
                $a['pay_state'] = 1;
                //生成内部订单号

                $a['out_trade_no'] = $v['order_id'] . '';
                $a['fee'] = $v2['sale_price'] / 100;
                $a['refund_fee'] = 0;
                if ($v['order_detail']['delivery_info']['address_info']['tel_number'] != '') {
                    $a['tel'] = $v['order_detail']['delivery_info']['address_info']['tel_number'];
                }
                if ($v['order_detail']['delivery_info']['address_info']['virtual_order_tel_number'] != '') {
                    $a['tel'] = $v['order_detail']['delivery_info']['address_info']['virtual_order_tel_number'];
                }
                $a['items'] = '英语课程费';
                $a['goods_detail'] = '[{"id":8,"fee":"' . ($v2['sale_price'] / 100) . '.00","name":"\u82f1\u8bed\u8bfe\u7a0b\u8d39"}]';
                $a['params'] = '{"remark":"\u8d2d\u4e70\u82f1\u8bed\u8bfe\u7a0b","price":"' . ($v2['sale_price'] / 100) . '.00","courseid":"' . $course['id'] . '",tichengtype":0,"ticheng":"0.00","tichengmoney":0.000}';
                $a['order_num'] = $v['order_id'] . '';
                $a['order_nums'] = $v['order_id'] . '';
                $a['result'] = '';
                // $a['isfinished'] = 1;
                $a['paymethod'] = 1;
                $a['flag'] = 9;
                $a['pay_time'] = $v['order_detail']['pay_info']['pay_time'];
                $a['refund_time'] = 0;
                $a['operator'] = '视频号-蓝图计划';
                $a['manager'] = '视频号-蓝图计划';
                $a['weapp_openid'] = $v['openid'];
                $a['ticheng'] = 0;
                $a['tichengmoney'] = 0;
                $a['tichengtype'] = 0;
                $a['laiyuan'] = 1;
                $a['province'] = $v['order_detail']['delivery_info']['address_info']['province_name'];
                $a['city'] = $v['order_detail']['delivery_info']['address_info']['city_name'];
                $a['county'] = $v['order_detail']['delivery_info']['address_info']['county_name'];
                $a['addr'] = $v['order_detail']['delivery_info']['address_info']['detail_info'];

                //前端显示数据
                $a['title'] = $v2['title'];
                if ($v['order_detail']['delivery_info']['address_info']['tel_number'] != '') {
                    $a['tel_number'] = $v['order_detail']['delivery_info']['address_info']['tel_number'];
                }
                if ($v['order_detail']['delivery_info']['address_info']['virtual_order_tel_number'] != '') {
                    $a['tel_number'] = $v['order_detail']['delivery_info']['address_info']['virtual_order_tel_number'];
                }
                $a['user_name'] = $v['order_detail']['delivery_info']['address_info']['user_name'];
                $a['city_name'] = $v['order_detail']['delivery_info']['address_info']['city_name'];
                $a['county_name'] = $v['order_detail']['delivery_info']['address_info']['county_name'];
                $a['create_time'] = $v['create_time'];

                $a['waijiao'] = $this->shoumaiguize($course['id']);  //售卖规则
                $a['i_id'] = $v2['product_id'];
                $a['shop_id'] = $appid;

                $orderlist[] = $a;

                //配送单
                $b = array();
                $b['order_num'] = $v['order_id'] . '';
                $b['order_time'] = strtotime($v['order_detail']['pay_info']['pay_time']);
                if ($v['order_detail']['delivery_info']['address_info']['tel_number'] != '') {
                    $b['tel'] = $v['order_detail']['delivery_info']['address_info']['tel_number'];
                }
                if ($v['order_detail']['delivery_info']['address_info']['virtual_order_tel_number'] != '') {
                    $b['tel'] = $v['order_detail']['delivery_info']['address_info']['virtual_order_tel_number'];
                }
                $b['name'] = $v['order_detail']['delivery_info']['address_info']['user_name'];
                $b['address'] = $v['order_detail']['delivery_info']['address_info']['province_name'] . $v['order_detail']['delivery_info']['address_info']['city_name'] . $v['order_detail']['delivery_info']['address_info']['county_name'] . $v['order_detail']['delivery_info']['address_info']['detail_info'];
                $b['goods'] = $course['title'];
                $b['laiyuan'] = 1;
                $b['time'] = time();
                $delivery[] = $b;

                //发短信
                // $sms = array();
                // $sms = explode('+', $a['tel']);
                // $res = \VodAPI::smsToMember($sms);
                // dump($res);
            }
        }

        // dump($orderlist);
        // dump($delivery);

        //添加新订单

        //向小雪花后台添加数据
        $this->addXXHOrder($orderlist, $state);
        return;
    }


    /**
     * 取消视频号1小商店订单  视频号-毛毛虫李洁的小店  
     */
    public function cancelOrder_shipinhao1($next = '')
    {
        header("Content-type: text/html; charset=utf-8");
        // $start_time = '1667318400';
        // $start_time = strtotime(date('Y-m-d H:i:s', time()) . '-1 day');
        // $end_time = strtotime(date('Y-m-d H:i:s', time()));
        $start_time = strtotime(date('Y-m-d', time()));
        $end_time = strtotime(date('Y-m-d H:i:s', time()));
        //获取本地存储的订单数组
        // $order = Db::table('xh_common')->where(array('keys'=>WEAPP_SHOP_ORDER))->getFields('values');
        // $order = unserialize($order);


        // 拉取视频号小商店待发货订单
        $accessToken = $this->getSPShopAccessToken();
        $queryUrl = 'https://api.weixin.qq.com/channels/ec/aftersale/getaftersalelist?access_token=' . $accessToken;
        $data = array();
        $data['begin_create_time'] = $start_time;
        $data['end_create_time'] = $end_time;
        if ($next != '') {
            $data['next_key'] = $next;
        }
        $template = json_encode($data);
        $order2 = Curl::callWebServer($queryUrl, $template, 'POST');
        dump($order2);

        //没有订单返回
        if (count($order2['after_sale_order_id_list']) == 0) {
            // $this->ajaxReturn(array('s'=>0,'msg'=>'小商店无订单','data'=>$order2));
            return;
        }


        //订单数组
        $ids = $order2['after_sale_order_id_list'];  //循环出小商店订单的订单号数组
        $addids = array();
        //与本地存储的数据进行比较排重，筛选出需要添加的订单
        $where = [];
        $where[] = ['order_num', 'in', $ids];
        $yiyou1 = Db::table('xh_order_1')->where($where)->field('order_num')->select()->toArray();
        $yiyou = array_column($yiyou1, 'order_num');

        if ($yiyou) {
            $addids = array_diff($ids, $yiyou);
        } else {
            $addids = $ids;
        }

        if (!$addids) {
            dump('重复订单，无需添加');

            //如果还有其他页数据，则循环继续
            dump($order2['has_more']);
            if ($order2['has_more']) {
                $this->cancelOrder_shipinhao1($order2['next_key']);
            }
            dump($order2['next_key']);
            return;
        }



        //根据orderid获取order详细信息
        foreach ($ids as $k => $v) {
            // 拉取视频号小商店待发货订单
            $accessToken = $this->getSPShopAccessToken();
            $queryUrl = 'https://api.weixin.qq.com/channels/ec/aftersale/getaftersaleorder?access_token=' . $accessToken;
            $data = array();
            $data['after_sale_order_id'] = $v;
            $template = json_encode($data);
            $data = Curl::callWebServer($queryUrl, $template, 'POST');
            dump($data);
            if ($data['errmsg'] != 'ok') {
                return;
            }
            $order2['orders'][] = $data['after_sale_order'];
        }


        $ids = array();
        foreach ($order2['orders'] as $k => $v) {
            $ids[] = $v['order_id'];
        }

        //组装订单数据
        foreach ($order2['orders'] as $k => $v) {
            if ($v['status'] == 'MERCHANT_REFUND_SUCCESS' || $v['status'] == 'MERCHANT_RETURN_SUCCESS') {  //退款完成  退货退款完成
                // if (in_array( $v['order_id'], $addids)) {
                $ding = Db::table('xh_order_1')->where('order_num', $v['order_id'])->find();
                if ($ding && $ding['courseid']) {
                    //订单退单
                    $refund_time = time();
                    //删除小雪花订单
                    $this->delXXHOrder($v['order_id'], $v['refund_info']['amount'], $refund_time);

                } else {
                    dump($v['order_id']);
                    $this->getDingDanFromSPShop_one($v['order_id'], 3);
                    //订单退单
                    $refund_time = time();
                    //删除小雪花订单
                    $this->delXXHOrder($v['order_id'], $v['refund_info']['amount'], $refund_time);
                }
                // }

            }
        }
        // $this->cancelOrder_shipinhao2();
        return;
    }

    /**
     * 取消视频号1小商店订单    视频号-毛毛虫李洁的小店
     */
    public function cancelOrder_shipinhao2($next = '')
    {
        header("Content-type: text/html; charset=utf-8");
        // $start_time = '1667318400';
        $start_time = strtotime(date('Y-m-d', time()));
        $end_time = strtotime(date('Y-m-d H:i:s', time()));

        //获取本地存储的订单数组
        // $order = Db::table('xh_common')->where(array('keys'=>WEAPP_SHOP_ORDER))->getFields('values');
        // $order = unserialize($order);


        // 拉取视频号小商店待发货订单
        $accessToken = $this->getSPShopAccessToken();
        $queryUrl = 'https://api.weixin.qq.com/channels/ec/aftersale/getaftersalelist?access_token=' . $accessToken;
        $data = array();
        $data['begin_create_time'] = $start_time;
        $data['end_create_time'] = $end_time;
        if ($next != '') {
            $data['next_key'] = $next;
        }
        $template = json_encode($data);
        $order2 = Curl::callWebServer($queryUrl, $template, 'POST');
        dump($order2);

        //没有订单返回
        if (count($order2['after_sale_order_id_list']) == 0) {
            // $this->ajaxReturn(array('s'=>0,'msg'=>'小商店无订单','data'=>$order2));
            return;
        }

        //订单数组
        $ids = $order2['after_sale_order_id_list'];  //循环出小商店订单的订单号数组
        $addids = array();
        //与本地存储的数据进行比较排重，筛选出需要添加的订单
        $where = [];
        $where[] = ['order_num', 'in', $ids];
        $yiyou1 = Db::table('xh_order_1')->where($where)->field('order_num')->select()->toArray();
        $yiyou = array_column($yiyou1, 'order_num');

        if ($yiyou) {
            $addids = array_diff($ids, $yiyou);
        } else {
            $addids = $ids;
        }

        if (!$addids) {
            dump('重复订单，无需添加');

            //如果还有其他页数据，则循环继续
            dump($order2['has_more']);
            if ($order2['has_more']) {
                $this->cancelOrder_shipinhao2($order2['next_key']);
            }
            dump($order2['next_key']);
            return;
        }


        //根据orderid获取order详细信息
        foreach ($ids as $k => $v) {
            // 拉取视频号小商店待发货订单
            $accessToken = $this->getSPShopAccessToken();
            $queryUrl = 'https://api.weixin.qq.com/channels/ec/aftersale/getaftersaleorder?access_token=' . $accessToken;
            $data = array();
            $data['after_sale_order_id'] = $v;
            $template = json_encode($data);
            $data = Curl::callWebServer($queryUrl, $template, 'POST');
            dump($data);
            if ($data['errmsg'] != 'ok') {

                return;
            }
            $order2['orders'][] = $data['after_sale_order'];
        }


        $ids = array();
        foreach ($order2['orders'] as $k => $v) {
            $ids[] = $v['order_id'];
        }



        //组装订单数据
        foreach ($order2['orders'] as $k => $v) {
            if ($v['status'] == 'MERCHANT_REFUND_SUCCESS' || $v['status'] == 'MERCHANT_RETURN_SUCCESS') {  //退款完成  退货退款完成
                if (in_array($v['order_id'], $addids)) {
                    $ding = Db::table('xh_order_1')->where('order_num', $v['order_id'])->find();
                    if ($ding && $ding['courseid']) {
                        //订单退单
                        $refund_time = time();

                        //删除小雪花订单
                        $this->delXXHOrder($v['order_id'], $v['refund_info']['amount'], $refund_time);

                    }
                }
            }
        }

        return;
    }


    /**
     * @author: zwx
     * @Description: 删除小雪花订单以及添加订单表
     * @param {*} $order_num
     * @param {*} $refund_fee
     * @param {*} $refund_time
     * @Date: 2024-03-14 20:23:34
     */
    function delXXHOrder($order_num, $refund_fee, $refund_time)
    {
        //新订单数据
        $where = [];
        $where[] = ['order_num', '=', $order_num];

        $order = Db::table('xh_order_1')->where($where)->find();

        if ($order) {
            $data = array();
            // $data['refund_fee'] = $refund_fee * 100;
            // $data['refund_time'] = date('Y-m-d H:i:s', $refund_time);
            $data['order_status'] = 3;

            Db::table('xh_order_1')->where($where)->save($data);

            $data = array();
            $data['state'] = 3;
            $data['out_refund_no'] = 'T' . $order['out_order_no'];
            $data['refund_time'] = date('Y-m-d H:i:s', $refund_time);
            Db::table('xh_ordernum')->where($where)->save($data);
            // M('refundorder_'.$ordernum['qiyeid'],'xh_',C('DB_CONFIG_XIAOXUEHUA'))->where(array('order_num'=>$order_num))->save($data);
        }

        $refund = Db::table('xh_refundorder_1')->where($where)->find();
        if (empty($refund)) {
            //添加退款单
            $data = array();
            $data['refund_id'] = '';
            $data['order_num'] = $order_num;
            $data['out_refund_no'] = 'T' . $order['out_order_no'];
            $data['out_order_no'] = $order['out_order_no'];
            $data['apply_time'] = date('Y-m-d H:i:s', $refund_time);
            $data['state'] = 3;
            $data['refund_time'] = date('Y-m-d H:i:s', $refund_time);
            $data['app_id'] = '';
            $data['fee'] = $refund_fee;
            // $data['time'] = date('Y-m-d H:i:s',$msg->create_refund_time/1000);
            // $data['remark'] = '['.implode(',',$msg->refund_reason).']-'.$msg->refund_description;

            Db::table('xh_refundorder_1')->insert($data);
        }



    }




    /**
     * @author: zwx
     * @Description: 售卖规则
     * @param {*} $courseid  课程ID
     *
     * @Date: 2024-08-31 17:28:32
     */
    public static function shoumaiguize($courseid)
    {

        $waijiao = '0';


        return $waijiao;

    }

    /************************************************** 打标签 ************************************************************************************/
    /**
     * @author: zwx
     * @Description: 存储标签到redis，然后消费打标签
     * @Date: 2024-04-24 23:49:21
     */
    public function dabiaoqian($data)
    {

        //初始化redis
        if ($data) {

            //压入redis缓存等待消费
            $liveStatus = new LiveStatus(0);
            $liveStatus->set_jst_dabiaoqain(json_encode($data));

        } else {
            file_put_contents('_dabiaoqian.txt', json_encode($data));
        }
        return json_encode(array('code' => 1, 'msg' => 'success'));

    }

    /**
     * @author: zwx
     * @Description: 给订单生成短编码  404180001
     * @param {*} $qiyeid   企业ID
     * @return {*} $code  生成的编码  404180001
     * @Date: 2024-04-18 14:58:23
     */
    function short_Code($qiyeid)
    {

        $where = array();
        $where['del'] = 0;
        $where['time'] = array(array('egt', date('Y-m-d')), array('lt', date('Y-m-d', time() + 86400)), 'AND');

        $num = Db::table('xh_order_1')->where($where)->count(); //所有订单

        $num++; //加一

        $num = str_pad($num, 5, "0", STR_PAD_LEFT); //不足补零

        $nian = date('y');
        $yue = date('m');
        $ri = date('d');

        $wan = substr($num, 0, 1);
        $qian = substr($num, 1, 1);
        $bai = substr($num, 2, 1);
        $shi = substr($num, 3, 1);
        $ge = substr($num, 4, 1);

        $code = $nian . $yue . $ri . $wan . $qian . $bai . $shi . $ge; //拼接   404180001

        return $code;

    }


    /***********************************************************************************************/

    //批量自动分配助教api
    public function batchAutoDistributionApi($orderNum)
    {

        if (is_array($orderNum)) {
            foreach ($orderNum as $item) {
                $ret[] = self::singleAutoDistribution($item, 1);
            }
        } else {
            $ret = self::singleAutoDistribution($orderNum, 1);
        }

    }



    //分配助教  $manner=0轮询，$manner=1权重
    public static function singleAutoDistribution($orderNum, $qiyeId)
    {
        $order = Db::table('xh_order_1')->where('order_num', $orderNum)->find();
        $where = [];
        $where[] = ['qiyeid', '=', 1];
        $where[] = ['pingtai_id', '=', $order['pingtai']];
        $loose = Db::table('xh_code_loose')->where($where)->find();
        if (empty($loose)) {
            $where = [];
            $where[] = ['code_loose_id', '=', $loose['id']];
            $where[] = ['default', '=', 1];
            $teacher = Db::table('xh_code_loose_teacher')->where($where)->find();
            Log::write('--自动分配活码--平台没有活码--【企业ID：' . $qiyeId . '】【平台ID：' . $order['pingtai'] . '】');
            //return 1; //平台没有活码
        } else {
            $map[] = ['crew', '>', 0];
            $map['del'] = ['del', '=', 0];
            $group = Db::table('xh_code_loose_group')->where($map)->order('id ASC')->select();
            if (empty($group)) {
                $teacher = self::lunXunZhuJiao($loose);  //轮询分配
            } else {
                foreach ($group as $item) {
                    if ($item['rule'] == 2) {
                        $teacher = self::quanZhongZhuJiao($loose, $item['id']);  //正序分配
                    } else if ($item['rule'] == 3) {
                        $teacher = self::quanZhongZhuJiao($loose, $item['id'], 1);  //倒序分配
                    } else {
                        $teacher = self::lunXunZhuJiao($loose, $item['id']);  //轮询分配
                    }
                    if (!empty($teacher)) {
                        break;
                    }
                }
            }
            if (empty($teacher)) {
                $where = [];
                $where[] = ['code_loose_id', '=', $loose['id']];
                $where[] = ['default', '=', 1];
                $teacher = Db::table('xh_code_loose_teacher')->where($where)->find();
                Log::write('--自动分配活码--平台没有备用助教--【企业ID：' . $qiyeId . '】【活码ID：' . $loose['id'] . '】');
            }
        }
        //$teacher_day = $teacher['pre_restrict_time']>0?$teacher['pre_restrict_time']:time();
        //$c_day = date('d');
        //$k_day = date('d', $teacher_day);
        //if ($c_day != $k_day) {
        //    Log::write('--分配：日期对比--');
        //    $updateData = [
        //        'log_rand'=>0,
        //        'status'=>0,
        //        'pre_points_cnt'=>0,
        //        'pre_restrict_time'=>time(),
        //    ];
        //    M('code_loose_teacher')->where(['code_loose_id'=>$loose['id']])->save($updateData);
        //    M('code_loose')->where(['id'=>$loose['id']])->save(['log_rand'=>0]);
        //    if ($teacher['type'] > 0) {
        //        Log::write('--分配：重置后重新取--');
        //        $teacher = self::lunXunZhuJiao($loose);
        //    }
        //}
        $where = [];
        $where[] = ['code_loose_id', '=', $loose['id']];
        $where[] = ['userid', '=', $teacher['userid']];
        $code = Db::table('xh_code_loose_code')->where($where)->find();
        $oc = Db::table('xh_order_code')->where('order_id', $order['id'])->find();
        if (empty($oc)) {
            $data = [
                'qiyeid' => $qiyeId,
                'order_id' => $order['id'],
                'pingtai_id' => $order['pingtai'],
                'union_id' => $order['wx_union_id'],
                'teacher_id' => $teacher['userid'],
                'qr_code' => $code['qr_code'],
                'time' => date('Y-m-d H:i:s', time()),
            ];
            //Log::write('--分配：创建分配，--data--'.json_encode($data, JSON_UNESCAPED_UNICODE));
            Log::write('--分配：创建分配，--data--');
            $ocId = Db::table('xh_order_code')->insert($data);
            if (!empty($ocId)) {
                Log::write('--分配：分配成功，--[' . $teacher['userid'] . ']-[' . $code['qr_code'] . ']-');
                //更新助教轮次
                Db::table('xh_code_loose_teacher')->where('id', $teacher['id'])->setInc('log_rand');
                //更新助教最后分配时间
                Db::table('xh_code_loose_teacher')->where('id', $teacher['id'])->save(['pre_restrict_time' => time()]);
                //更新分配计数
                Db::table('xh_code_loose_teacher')->where('id', $teacher['id'])->setInc('pre_points_cnt');
                Db::table('xh_code_loose_teacher')->where('id', $teacher['id'])->setInc('pre_total_cnt');
                //数超过或等于限制，禁用助教
                $teacher = Db::table('xh_code_loose_teacher')->where('id', $teacher['id'])->find();
                if ($teacher['restrict_cnt'] > 0) {
                    if ($teacher['pre_points_cnt'] >= $teacher['restrict_cnt']) {
                        Log::write('--分配：分配超限--禁用助教--[' . $teacher['teacher_id'] . ']--');
                        Db::table('xh_code_loose_teacher')->where('id', $teacher['id'])->save(['status' => 1]);
                    }
                }
            } else {
                Log::write('--自动分配活码--入order_code失败--【企业ID：' . $qiyeId . '】【活码ID：' . $loose['id'] . '】');
            }
            $oc = Db::table('xh_order_code')->where('order_id', $order['id'])->find();
        }
        return $oc;
    }


    //轮询
    public static function lunXunZhuJiao($loose, $groupId = 0, $turn = 0)
    {
        $logRandNum = empty($loose['log_rand']) ? 0 : $loose['log_rand'];
        $map = ['code_loose_id' => $loose['id'], 'log_rand' => $logRandNum, 'type' => 0, 'status' => 0, 'del' => 0, 'default' => 0];
        if ($groupId > 0) {
            $map['group_id'] = $groupId;
        }
        $teacher = Db::table('xh_code_loose_teacher')->where($map)->order('id ASC')->find();
        if (empty($teacher)) {
            $where = ['code_loose_id' => $loose['id'], 'type' => 0, 'status' => 0, 'del' => 0, 'default' => 0];
            if ($groupId > 0) {
                $where['group_id'] = $groupId;
            }
            $teacher = Db::table('xh_code_loose_teacher')->where($where)->orderRaw('rand()')->find();
            if (empty($teacher)) {
                return false;
            }
            $turn = $turn + 1;
            if ($turn > 3) {
                $save_where = ['code_loose_id' => $loose['id'], 'del' => 0, 'default' => 0];
                if ($groupId > 0) {
                    $save_where['group_id'] = $groupId;
                }
                Db::table('xh_code_loose_teacher')->where($save_where)->save(['log_rand' => 0]);
                Db::table('xh_code_loose')->where('id', $loose['id'])->save(['log_rand' => 0]);
                $turn = 0;
                Log::write('--轮询分配助教超过3轮-随机分配1个---');
            } else {
                Db::table('xh_code_loose')->where('id', $loose['id'])->setInc('log_rand');
            }
            $loose = Db::table('xh_code_loose')->where('id', $loose['id'])->find();
            return self::lunXunZhuJiao($loose, $groupId, $turn);
        }
        return $teacher;
    }

    //权重
    public static function quanZhongZhuJiao($loose, $groupId, $sort = 0)
    {
        $where = ['code_loose_id' => $loose['id'], 'group_id' => $groupId, 'type' => 0, 'status' => 0, 'del' => 0, 'default' => 0];
        if ($sort > 0) {
            $order = 'id DESC';
        } else {
            $order = 'id ASC';
        }
        return Db::table('xh_code_loose_teacher')->where($where)->order($order)->find();
    }



}